<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Attack extends CI_Controller
{
    /*
    * Load for upgrade infomation user
    */
    public $_food;
    public $_wood;
    public $_metal;
    public $_petroleum;
    /*
    * End load
    */
	function Attack()
	{
		parent::__construct();
        /*
        * Load for upgrade infomation user
        */
        $this->_food = $this->config->item('food');
		$this->_wood = $this->config->item('wood');
		$this->_metal = $this->config->item('metal');
		$this->_petroleum = $this->config->item('petroleum');
        $this->load->model('common/common_model');
        /*
        * End load
        */
		$this->load->model('attack/attack_model');
	}
	
	public function index()
	{
        /*
        * Load for upgrade infomation user
        */
        //check lai
        $land = 1;
        $uid = $this->session->userdata('uid');
        $this->update_all_res_user($uid, $land);
        $this->update_all_info_user($uid);
        $rInfo = $this->run_time_res($uid);
        $data = array();
        $data['rfood'] = $rInfo[0];
        $data['rwood'] = $rInfo[1];
        $data['rmetal'] = $rInfo[2];
        $data['rpetroleum'] = $rInfo[3];
        $res = $this->common_model->ww_get_res_user_info_by_field($uid);
        $data['res'] = $res;
        $data['res']['food'] = $res['food'] > $res['maxstore'] ? $res['maxstore'] : $res['food'];
        $data['res']['wood'] = $res['wood'] > $res['maxstore'] ? $res['maxstore'] : $res['wood'];
        $data['res']['metal'] = $res['metal'] > $res['maxstore'] ? $res['maxstore'] : $res['metal'];
        $data['res']['petroleum'] = $res['petroleum'] > $res['maxstore'] ? $res['maxstore'] : $res['petroleum'];
        /*
        * End load
        */
		// header
		
		// content
		$this->load->view('attack/attack_view', $data);
		
		// foter
	}
    
	public function send_troops()
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		// check session user
		$arr_stroop = array(
			'u2', // linh bo binh
			'u3', // linh ban tia
			'u4', // linh chong tang
			'u5', // xe chien dau bo binh
			'u6', // xe thiet giap cho quan
			'u7', // xe thiet giap trinh sat
			'u8', // xe thiet giap chong min
			'u9', // xe thiet giap boc thep
			'u10', // xe tang hanh nhe
			'u11', // xe tang chien dau chu luc
			'u12', // sung coi
			'u13', // son phao
			'u14', // luu phao
			'u15', // phao phan luc
			'u16', // phao tu hanh
			'u17', // phao cao xa
			'u18', // phao phong khong tu hanh
			'u19', //
			'u20', //
			'u21', //
			'u22', //
			'u23', //
			'u24', //
			'u25', //
			'u26', //
			'u27', //
			'u28', //
			'u29', //
			'u30', //
			'u31', //
			'u32', //
			'u33', //
			'u34', //
			'u35', //
			'u36', //
			'u37', //
			'u38', //
			'u39', //
			'u40', //
			'u41', //
			'u42', //
			'u43', //
			'u44', //
			'u45', //
			'u46', //
			'u47', //
			'u48', //
			'u49', //
			'u50', //
			'u51', //
			'u52', //
			'u53', //
			'u54', //
			'u55', //
			'u56', //
			'u57', //
			'u58', //
			'u59', //
			'u60', //
			'u61', //
			'u62', //
			'u63', //
			'u64', //
			'u65', //
		);
		
		$sunit = $this->input->post('obj');
		$val = (int)$this->input->post('val');
		
		// check ton tai trong unit
		$chk_arrUnit = !in_array($sunit, $arr_unit) ? true : false;
		// kiem tra lai tren db
		
		// tru tai nguyen
		
		// update them don vi
		
		//check lai
        $land = 1;
        $pos = 0;
		$uid = $this->session->userdata('uid');
		$sunit = substr($sunit,1);
		$quantity = $lquantity = $val;
		$timestamp = time();
		$fixtime = 20;
		$status = 0;
		//
		$eachtime = $fixtime*$val;
		//trainning units
		$this->home_model->ww_update_training_military($uid, $land, $pos, $sunit, $lquantity, $timestamp, $eachtime, $fixtime, $status);
		
		//update units
		//$this->home_model->ww_update_quantity_military($uid, $land, $pos, $sunit, $val);
	}
    
    /*
    * -------------------------------------------------------------------------------------
    * Load for upgrade infomation user
    */
    /*
    * get resource from source
    */
	function run_time_res($uid)
	{
		$food = 60000/($this->_food/60);
		$wood = 60000/($this->_wood/60);
		$metal = 60000/($this->_metal/60);
		$petroleum = 60000/($this->_petroleum/60);
		
		$result = array($food, $wood, $metal, $petroleum);
		return $result;
	}
    /*
    * update resource to db
    */
    function update_all_res_user($uid, $land)
	{
		$data = array();
		$food = $this->_food;
		$wood = $this->_wood;
		$metal = $this->_metal;
		$petroleum = $this->_petroleum;
		$time = time();
		$res = $this->common_model->ww_get_res_user_info_by_field($uid);
		
		$lastupdate = $res['lastupdate'];
		
		$valFloat = (((($time - $lastupdate)/60)/60)/2);
		$food = floor($valFloat*$food);
		$wood = floor($valFloat*$wood);
		$metal = floor($valFloat*$metal);
		$petroleum = floor($valFloat*$petroleum);
        
        $food = $res['maxstore'] < $res['food'] + $food ? $res['maxstore'] - $res['food'] : $food;
        $wood = $res['maxstore'] < $res['wood'] + $wood ? $res['maxstore'] - $res['wood'] : $wood;
        $metal = $res['maxstore'] < $res['metal'] + $metal ? $res['maxstore'] - $res['metal'] : $metal;
        $petroleum = $res['maxstore'] < $res['petroleum'] + $petroleum ? $res['maxstore'] - $res['petroleum'] : $petroleum;
        
		if($food >= 1 || $wood >= 1 || $metal >= 1 || $petroleum >= 1)
		{
			$update_res_by_hour = $this->common_model->ww_update_res_by_hour($uid, $land, $food, $wood, $metal, $petroleum, $time);
		}
	}
    
    /*
    * update building for user
    */
    function upgrade_build_for_user($uid, $land)
    {
        $upgrade = $this->common_model->ww_get_user_info_build($uid, $land);
        /*
        check 
        */
        $arr_v1 = array();// build complete.
        $arr_v2 = array();// build close complete.
        $build_v2 = array();
        $chk_complete = false;
        foreach($upgrade as $lst)
        {
            $time_of_upgrade = $lst['timestamp'] + $lst['eachtime'];
            $now = time();
            $pastTime = $now - $time_of_upgrade;
            if($pastTime >= 0)
            {
                // complete
                $arr_v1['id'][] = $lst['id'];
                $arr_v1['buildid'][] = $lst['buildid'];
                $chk_complete = true;
            }
            else
            {
                // close complete
                $arr_v2['id'] = $lst['id'];
                $arr_v2['rtime'] = $lst['timestamp'] + $lst['eachtime'] - $now;
                $build_v2[] = $arr_v2;
            }
        }
       
        $strSuccess = '';
		if($chk_complete)
		{
			$lstid = join(",", $arr_v1['id']);
            $i=0;
			foreach($arr_v1['buildid'] as $lstBuild)
			{
				$strSuccess .= 'b'.$lstBuild.'=b'.$lstBuild.'+1,';
				$i++;
			}
            $strSuccess = substr($strSuccess, 0, -1);
            
			$this->common_model->ww_update_build_by_user($uid, $land, $strSuccess, $lstid);
		}
        return $build_v2;
    }
    
	public function update_all_info_user($uid)
	{
	   if(!$this->session->userdata('username'))
       {
            redirect(site_url('login'));
            die();
       }
		/*
		* update_all_info_user
		*/
		$info_train = $this->common_model->ww_get_train_user_info($uid, 0);
		
		$arrUnit = array();
		$arrVal = array();
		$strSuccess = '';
		$chkExistsCompleteTrain = false;
		foreach($info_train as $info)
		{
			// dat thoi gian tre khoang 5s.
			$timestamp = $info['timestamp'] + $info['eachtime'] + 5;
			$timenow = time();
			
			if($timenow > $timestamp)
			{
				/*
				* check id nhung traning da dc hoan thanh.
				*/
				$arrIDSuccess[] = $info['id'];
				if(!in_array('u'.$info['unit'], $arrUnit))
				{
					$arrUnit[] = 'u'.$info['unit'];
					$arrVal[] = $info['lquantity'] - $info['quantity'];
				}
				else
				{
					$valKey = array_search('u'.$info['unit'], $arrUnit);
					$arrVal[$valKey] = $arrVal[$valKey] + $info['lquantity'] - $info['quantity'];
				}
				$chkExistsCompleteTrain = true;
			}
			else
			{
				/*
				* check id nhung traning chua hoan thanh, chay thoi gian.
				*/
				
				// thoi gian hoan thanh tren db.
				$chkTime_v1 = $info['timestamp'] + $info['eachtime'];
				// thoi gian hien tai + thoi gian chuan hoan thanh khong tinh thoi gian traning truoc.
				$chkTime_v2 = $timenow + $info['fixtime']*$info['lquantity'];
				
				// thoi gian hoan thanh - thoi gian can ban de lay thoi gian du.
				$chkTime_v3 = $info['eachtime'] - $info['fixtime']*$info['lquantity'];
				
				
				// neu thoi gian 2 > thoi gian 1-> thoi gian hien tai da chuan bi hoan thanh
				//, kiem tra traning do'.
				if($chkTime_v2 > $chkTime_v1)
				{
					// gia tri $quantity la so nguyen to cua so luong da hoan thanh.
					$decimal = ($timenow - ($info['timestamp']+$chkTime_v3))/$info['fixtime'];
					$quantity = floor($decimal);
					$quantity = $quantity > $info['lquantity'] ? $info['lquantity'] : $quantity;
					
					if($decimal >= 1 && $quantity>=1 && $quantity > $info['quantity'])
					{
						$quantity = $quantity - $info['quantity'];
                        $this->common_model->ww_update_quantity_for_time($info['id'], $uid, $quantity);
					}
				}
			}
			// end if
		}
		/*
		* thao tac hoan thanh len db.
		*/
        
		if($chkExistsCompleteTrain)
		{
			$arrStr = array();
			$lstid = join(",", $arrIDSuccess);
			$i = 0;
			foreach($arrUnit as $typeUnit)
			{
				$strSuccess .= $typeUnit.'='.$typeUnit.'+'.$arrVal[$i].',';
				$i++;
			}
			$strSuccess = substr($strSuccess, 0, -1);
			$this->home_model->ww_update_quantity_military($uid, $strSuccess, $lstid);
		}
		// end for
	}
    /*
    * ------------------------------------------------------------------------------
    * End load
    */
}